package com.linchong.concurrency.chapter9;

import lombok.extern.slf4j.Slf4j;

import java.util.stream.Stream;

/**
 * @Author:linchong
 * @CreateTime:2020-01-09 16:12
 * @Description:wait和sleep区别
 */
@Slf4j
public class DifferenceOfWaitAndSleep {
	public static void main(String[] args) {
		//m1();
		//m2();
		//sleep不会释放锁，有明显的的先后顺序
		/*Stream.of("T1","T2").forEach(name->
			new Thread(name){
				@Override
				public void run() {
					m3();
				}
			}.start()
		);*/
		//wait会释放锁，两个线程几乎同时进入，然后进入waiting queue中，等待其他线程唤醒它们
		//否则一直等待
		Stream.of("T1", "T2").forEach(name ->
				new Thread(name) {
					@Override
					public void run() {
						m4();
					}
				}.start()
		);
	}

	private static Object LOCK = new Object();

	public static void m1() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void m2() {
		synchronized (LOCK) {
			try {
				LOCK.wait();
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void m3() {
		synchronized (LOCK) {
			try {
				log.info("The Thread:{} enter...", Thread.currentThread().getName());
				Thread.sleep(20000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void m4() {
		synchronized (LOCK) {
			try {
				log.info("The Thread:{} enter...", Thread.currentThread().getName());
				LOCK.wait();
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}


}
